const express=require("express");
const r=express.Router();
const pool=require("../pool");
r.use("/",(req,res,next)=>{
    var n=400;
    for(var k in req.body){
        n++;
        if(!req.body[k]){
            res.send({code:n,msg:k+"不能为空"});
            return;
        }
    }
    next();
});
//添加商品
r.post("/add",(req,res,next)=>{
    pool.query("INSERT INTO merchandises SET ?",[req.body],(err,result)=>{
        if(err){
            next(err);
            return;
        }
        res.send({code:200,msg:"添加成功"});
    })
})
//删除商品
r.delete("/:mid",(req,res,next)=>{
    pool.query("DELETE FROM merchandises WHERE mid=?",[req.params.mid],(err,result)=>{
        if(err){
            next(err);
            return;
        }
        result.affectedRows?res.send({code:200,msg:"删除成功"}):res.send({code:201,msg:"删除失败"})
    })
})
//修改商品
r.put("/",(req,res,next)=>{
    pool.query("UPDATE merchandises SET ? WHERE mid=?",[req.body,req.body.mid],(err,result)=>{
        if(err){
            next(err);
            return;
        }
        res.send(result.affectedRows?{code:200,msg:"修改成功"}:{code:201,msg:"修改失败"});
    })
})
//商品列表
r.get("/",(req,res,next)=>{
    pool.query("SELECT * FROM merchandises",(err,result)=>{
        if(err){
            next(err);
            return;
        }
        res.send({code:200,msg:"修改成功",data:result})
    })
})
//按照编号查询商品
r.get("/:mid",(req,res,next)=>{
    pool.query("SELECT * FROM merchandises WHERE mid=?",[req.params.mid],(err,result)=>{
        if(err){
            next(err);
            return;
        }
        res.send(result.length?{code:200,msg:"查找成功",data:result[0]}:{code:201,msg:"查找失败"});
    })
})
module.exports=r;